"""
Web客户端兼容性路由
为现有的Web客户端提供兼容的API接口
"""

from fastapi import APIRouter, HTTPException, Query, Form, UploadFile, File
from fastapi.responses import JSONResponse
from typing import Optional, List
import time

from ..storage import data_manager
from ..logger import logger
from ..services.event_dispatcher import event_dispatcher, EventType

router = APIRouter()


@router.get("/models")
async def get_models_compat():
    """获取模型列表 - Web客户端兼容接口"""
    try:
        # 获取所有模型
        models = await data_manager.get_models()
        
        # 转换为Web客户端期望的格式
        web_models = []
        for model in models:
            web_model = {
                "name": model.name,
                "filename": f"{model.name}.pt",  # 假设文件名
                "type": model.model_type,
                "size": model.size,
                "description": model.description,
                "author": model.author,
                "version": model.version,
                "upload_time": model.upload_time,
                "file_size": 0,  # 需要从实际文件获取
                "available": model.status == "available",
                "loaded": False,  # 需要从推理服务获取
                "active": False,  # 需要从推理服务获取
                "usage_count": 0,  # 需要从统计数据获取
                "source": "subscription" if model.server_id != "local" else "upload"
            }
            web_models.append(web_model)
        
        return {
            "success": True,
            "models": web_models,
            "total": len(web_models),
            "timestamp": time.time()
        }
        
    except Exception as e:
        logger.error(f"Failed to get models for web client: {e}")
        return {
            "success": False,
            "error": str(e),
            "models": [],
            "total": 0
        }


@router.post("/models/upload")
async def upload_model_compat(
    file: UploadFile = File(...),
    name: str = Form(...),
    model_type: str = Form(...),
    description: str = Form(default=""),
    version: str = Form(default="1.0.0"),
    author: str = Form(default="")
):
    """上传模型 - Web客户端兼容接口"""
    try:
        # 这里应该实现实际的文件上传逻辑
        # 目前只是模拟创建模型记录
        
        from ..storage import ModelInfo
        from ..utils import generate_id
        
        current_time = time.time()
        
        new_model = ModelInfo(
            id=generate_id(),
            name=name,
            version=version,
            model_type=model_type,
            description=description,
            author=author,
            size="m",  # 默认中等大小
            upload_time=current_time,
            last_update=current_time,
            status="available",
            download_url="",
            checksum="",
            server_id="local",
            tags=[],
            requirements={},
            metrics={}
        )
        
        await data_manager.add_model(new_model)
        
        # 发出模型上传事件
        await event_dispatcher.emit(
            EventType.MODEL_DISCOVERED,
            {
                "model_id": new_model.id,
                "model_name": new_model.name,
                "model_version": new_model.version,
                "upload_method": "file"
            },
            "web_client"
        )
        
        return {
            "success": True,
            "message": f"Model {name} uploaded successfully",
            "model_id": new_model.id
        }
        
    except Exception as e:
        logger.error(f"Failed to upload model: {e}")
        return {
            "success": False,
            "error": str(e)
        }


@router.post("/models/upload-url")
async def upload_model_url_compat(
    url: str = Form(...),
    name: str = Form(...),
    model_type: str = Form(...),
    description: str = Form(default=""),
    version: str = Form(default="1.0.0"),
    author: str = Form(default="")
):
    """URL下载模型 - Web客户端兼容接口"""
    try:
        from ..storage import ModelInfo
        from ..utils import generate_id
        
        current_time = time.time()
        
        new_model = ModelInfo(
            id=generate_id(),
            name=name,
            version=version,
            model_type=model_type,
            description=description,
            author=author,
            size="m",
            upload_time=current_time,
            last_update=current_time,
            status="available",
            download_url=url,
            checksum="",
            server_id="local",
            tags=[],
            requirements={},
            metrics={}
        )
        
        await data_manager.add_model(new_model)
        
        # 发出模型上传事件
        await event_dispatcher.emit(
            EventType.MODEL_DISCOVERED,
            {
                "model_id": new_model.id,
                "model_name": new_model.name,
                "model_version": new_model.version,
                "upload_method": "url",
                "download_url": url
            },
            "web_client"
        )
        
        return {
            "success": True,
            "message": f"Model {name} downloaded successfully",
            "model_id": new_model.id,
            "download_info": {
                "file_size": 0,
                "download_time": 0
            }
        }
        
    except Exception as e:
        logger.error(f"Failed to download model: {e}")
        return {
            "success": False,
            "error": str(e)
        }


@router.delete("/models/{model_name}")
async def delete_model_compat(model_name: str):
    """删除模型 - Web客户端兼容接口"""
    try:
        # 查找模型
        models = await data_manager.get_models()
        model_to_delete = None
        
        for model in models:
            if model.name == model_name:
                model_to_delete = model
                break
        
        if not model_to_delete:
            return {
                "success": False,
                "error": "Model not found"
            }
        
        # 删除模型
        await data_manager.delete_model(model_to_delete.id)
        
        # 发出模型删除事件
        await event_dispatcher.emit(
            EventType.MODEL_DELETED,
            {
                "model_id": model_to_delete.id,
                "model_name": model_to_delete.name,
                "model_version": model_to_delete.version
            },
            "web_client"
        )
        
        return {
            "success": True,
            "message": f"Model {model_name} deleted successfully"
        }
        
    except Exception as e:
        logger.error(f"Failed to delete model {model_name}: {e}")
        return {
            "success": False,
            "error": str(e)
        }


@router.get("/models/statistics")
async def get_statistics_compat():
    """获取统计信息 - Web客户端兼容接口"""
    try:
        # 获取模型统计
        models = await data_manager.get_models()
        subscriptions = await data_manager.get_subscriptions()
        servers = await data_manager.get_servers()
        
        # 统计各种信息
        total_models = len(models)
        total_subscriptions = len(subscriptions)
        total_servers = len(servers)
        
        # 按类型统计模型
        models_by_type = {}
        for model in models:
            model_type = model.model_type
            models_by_type[model_type] = models_by_type.get(model_type, 0) + 1
        
        # 按状态统计
        active_subscriptions = len([s for s in subscriptions if s.status == "active"])
        online_servers = len([s for s in servers if s.status == "online"])
        
        # 系统信息
        system_info = {
            "version": "1.0.0",
            "uptime": time.time(),
            "api_version": "v1"
        }
        
        return {
            "success": True,
            "statistics": {
                "total_models": total_models,
                "total_subscriptions": total_subscriptions,
                "total_servers": total_servers,
                "active_subscriptions": active_subscriptions,
                "online_servers": online_servers,
                "models_by_type": models_by_type,
                "system_info": system_info
            },
            "timestamp": time.time()
        }
        
    except Exception as e:
        logger.error(f"Failed to get statistics: {e}")
        return {
            "success": False,
            "error": str(e),
            "statistics": {}
        }


# 订阅相关的兼容接口
@router.get("/subscription/servers")
async def get_subscription_servers():
    """获取订阅服务器列表"""
    try:
        servers = await data_manager.get_servers()
        
        server_list = []
        for server in servers:
            server_info = {
                "id": server.id,
                "name": server.name,
                "url": server.url,
                "status": server.status,
                "last_check": server.last_check
            }
            server_list.append(server_info)
        
        return {
            "success": True,
            "servers": server_list
        }
        
    except Exception as e:
        logger.error(f"Failed to get subscription servers: {e}")
        return {
            "success": False,
            "error": str(e),
            "servers": []
        }


@router.post("/subscription/servers")
async def add_subscription_server(
    name: str = Form(...),
    url: str = Form(...)
):
    """添加订阅服务器"""
    try:
        from ..storage import SubscriptionServer
        from ..utils import generate_id
        
        new_server = SubscriptionServer(
            id=generate_id(),
            name=name,
            url=url.rstrip('/'),
            api_key=None,
            status="offline",
            last_check=None,
            check_interval=1800,
            consecutive_errors=0
        )
        
        await data_manager.add_server(new_server)
        
        return {
            "success": True,
            "message": f"Server {name} added successfully",
            "server_id": new_server.id
        }
        
    except Exception as e:
        logger.error(f"Failed to add subscription server: {e}")
        return {
            "success": False,
            "error": str(e)
        }


@router.delete("/subscription/servers/{server_id}")
async def remove_subscription_server(server_id: str):
    """删除订阅服务器"""
    try:
        await data_manager.delete_server(server_id)
        
        return {
            "success": True,
            "message": "Server removed successfully"
        }
        
    except Exception as e:
        logger.error(f"Failed to remove subscription server: {e}")
        return {
            "success": False,
            "error": str(e)
        }


@router.post("/models/{model_name}/deploy")
async def deploy_model_compat(model_name: str, client_id: Optional[str] = None):
    """部署模型 - Web客户端兼容接口"""
    try:
        # 查找模型
        models = await data_manager.get_models()
        model_to_deploy = None

        for model in models:
            if model.name == model_name:
                model_to_deploy = model
                break

        if not model_to_deploy:
            return {
                "success": False,
                "error": "Model not found"
            }

        # 获取在线的pyolo客户端
        from .clients import get_pyolo_client_info
        pyolo_clients = await get_pyolo_client_info()

        if not pyolo_clients:
            return {
                "success": False,
                "error": "No pyolo clients available for deployment"
            }

        # 选择目标客户端
        import aiohttp
        if client_id:
            # 查找指定的客户端
            client_info = None
            for client in pyolo_clients:
                if client["client_id"] == client_id:
                    client_info = client
                    break

            if not client_info:
                return {
                    "success": False,
                    "error": f"Client {client_id} not found or offline"
                }
        else:
            # 使用第一个可用的客户端
            client_info = pyolo_clients[0]
        base_url = f"http://{client_info['ip_address']}:{client_info['port']}"

        try:
            async with aiohttp.ClientSession() as session:
                async with session.post(
                    f"{base_url}/models/{model_name}/deploy",
                    timeout=aiohttp.ClientTimeout(total=30)
                ) as response:
                    if response.status == 200:
                        result = await response.json()

                        # 发出模型部署事件
                        await event_dispatcher.emit(
                            EventType.MODEL_UPDATED,
                            {
                                "model_id": model_to_deploy.id,
                                "model_name": model_to_deploy.name,
                                "model_version": model_to_deploy.version,
                                "model_type": model_to_deploy.model_type,
                                "action": "deploy",
                                "client_id": client_info["client_id"]
                            },
                            "web_client"
                        )

                        return {
                            "success": True,
                            "message": f"Model {model_name} deployed successfully on {client_info['client_id']}"
                        }
                    else:
                        error_text = await response.text()
                        return {
                            "success": False,
                            "error": f"Deployment failed: {error_text}"
                        }
        except Exception as e:
            return {
                "success": False,
                "error": f"Failed to connect to pyolo client: {str(e)}"
            }

    except Exception as e:
        logger.error(f"Failed to deploy model {model_name}: {e}")
        return {
            "success": False,
            "error": str(e)
        }


@router.post("/models/{model_name}/stop")
async def stop_model_compat(model_name: str, client_id: Optional[str] = None):
    """停止模型 - Web客户端兼容接口"""
    try:
        # 查找模型
        models = await data_manager.get_models()
        model_to_stop = None

        for model in models:
            if model.name == model_name:
                model_to_stop = model
                break

        if not model_to_stop:
            return {
                "success": False,
                "error": "Model not found"
            }

        # 获取在线的pyolo客户端
        from .clients import get_pyolo_client_info
        pyolo_clients = await get_pyolo_client_info()

        if not pyolo_clients:
            return {
                "success": False,
                "error": "No pyolo clients available for stopping model"
            }

        # 选择目标客户端
        import aiohttp
        if client_id:
            # 查找指定的客户端
            client_info = None
            for client in pyolo_clients:
                if client["client_id"] == client_id:
                    client_info = client
                    break

            if not client_info:
                return {
                    "success": False,
                    "error": f"Client {client_id} not found or offline"
                }
        else:
            # 使用第一个可用的客户端
            client_info = pyolo_clients[0]
        base_url = f"http://{client_info['ip_address']}:{client_info['port']}"

        try:
            async with aiohttp.ClientSession() as session:
                async with session.post(
                    f"{base_url}/models/{model_name}/stop",
                    timeout=aiohttp.ClientTimeout(total=30)
                ) as response:
                    if response.status == 200:
                        result = await response.json()

                        # 发出模型停止事件
                        await event_dispatcher.emit(
                            EventType.MODEL_UPDATED,
                            {
                                "model_id": model_to_stop.id,
                                "model_name": model_to_stop.name,
                                "model_version": model_to_stop.version,
                                "model_type": model_to_stop.model_type,
                                "action": "stop",
                                "client_id": client_info["client_id"]
                            },
                            "web_client"
                        )

                        return {
                            "success": True,
                            "message": f"Model {model_name} stopped successfully on {client_info['client_id']}"
                        }
                    else:
                        error_text = await response.text()
                        return {
                            "success": False,
                            "error": f"Stop failed: {error_text}"
                        }
        except Exception as e:
            return {
                "success": False,
                "error": f"Failed to connect to pyolo client: {str(e)}"
            }

    except Exception as e:
        logger.error(f"Failed to stop model {model_name}: {e}")
        return {
            "success": False,
            "error": str(e)
        }


@router.post("/clients/{client_id}/models/{model_name}/deploy")
async def deploy_model_to_client(client_id: str, model_name: str):
    """部署模型到指定客户端"""
    try:
        # 查找模型
        models = await data_manager.get_models()
        model_to_deploy = None

        for model in models:
            if model.name == model_name:
                model_to_deploy = model
                break

        if not model_to_deploy:
            return {
                "success": False,
                "error": "Model not found"
            }

        # 获取指定客户端信息
        from .clients import get_pyolo_client_info
        pyolo_clients = await get_pyolo_client_info()

        client_info = None
        for client in pyolo_clients:
            if client["client_id"] == client_id:
                client_info = client
                break

        if not client_info:
            return {
                "success": False,
                "error": f"Client {client_id} not found or offline"
            }

        # 调用指定客户端进行部署
        import aiohttp
        base_url = f"http://{client_info['ip_address']}:{client_info['port']}"

        try:
            async with aiohttp.ClientSession() as session:
                async with session.post(
                    f"{base_url}/models/{model_name}/deploy",
                    timeout=aiohttp.ClientTimeout(total=30)
                ) as response:
                    if response.status == 200:
                        result = await response.json()

                        # 发出模型部署事件
                        await event_dispatcher.emit(
                            EventType.MODEL_UPDATED,
                            {
                                "model_id": model_to_deploy.id,
                                "model_name": model_to_deploy.name,
                                "model_version": model_to_deploy.version,
                                "model_type": model_to_deploy.model_type,
                                "action": "deploy",
                                "client_id": client_info["client_id"]
                            },
                            "web_client"
                        )

                        return {
                            "success": True,
                            "message": f"Model {model_name} deployed successfully on {client_info['client_id']}",
                            "client_info": {
                                "client_id": client_info["client_id"],
                                "name": client_info["name"],
                                "ip": client_info["ip_address"],
                                "port": client_info["port"]
                            }
                        }
                    else:
                        error_text = await response.text()
                        return {
                            "success": False,
                            "error": f"Deployment failed: {error_text}"
                        }
        except Exception as e:
            return {
                "success": False,
                "error": f"Failed to connect to client {client_id}: {str(e)}"
            }

    except Exception as e:
        logger.error(f"Failed to deploy model {model_name} to client {client_id}: {e}")
        return {
            "success": False,
            "error": str(e)
        }


@router.post("/clients/{client_id}/models/{model_name}/stop")
async def stop_model_on_client(client_id: str, model_name: str):
    """停止指定客户端上的模型"""
    try:
        # 查找模型
        models = await data_manager.get_models()
        model_to_stop = None

        for model in models:
            if model.name == model_name:
                model_to_stop = model
                break

        if not model_to_stop:
            return {
                "success": False,
                "error": "Model not found"
            }

        # 获取指定客户端信息
        from .clients import get_pyolo_client_info
        pyolo_clients = await get_pyolo_client_info()

        client_info = None
        for client in pyolo_clients:
            if client["client_id"] == client_id:
                client_info = client
                break

        if not client_info:
            return {
                "success": False,
                "error": f"Client {client_id} not found or offline"
            }

        # 调用指定客户端进行停止
        import aiohttp
        base_url = f"http://{client_info['ip_address']}:{client_info['port']}"

        try:
            async with aiohttp.ClientSession() as session:
                async with session.post(
                    f"{base_url}/models/{model_name}/stop",
                    timeout=aiohttp.ClientTimeout(total=30)
                ) as response:
                    if response.status == 200:
                        result = await response.json()

                        # 发出模型停止事件
                        await event_dispatcher.emit(
                            EventType.MODEL_UPDATED,
                            {
                                "model_id": model_to_stop.id,
                                "model_name": model_to_stop.name,
                                "model_version": model_to_stop.version,
                                "model_type": model_to_stop.model_type,
                                "action": "stop",
                                "client_id": client_info["client_id"]
                            },
                            "web_client"
                        )

                        return {
                            "success": True,
                            "message": f"Model {model_name} stopped successfully on {client_info['client_id']}",
                            "client_info": {
                                "client_id": client_info["client_id"],
                                "name": client_info["name"],
                                "ip": client_info["ip_address"],
                                "port": client_info["port"]
                            }
                        }
                    else:
                        error_text = await response.text()
                        return {
                            "success": False,
                            "error": f"Stop failed: {error_text}"
                        }
        except Exception as e:
            return {
                "success": False,
                "error": f"Failed to connect to client {client_id}: {str(e)}"
            }

    except Exception as e:
        logger.error(f"Failed to stop model {model_name} on client {client_id}: {e}")
        return {
            "success": False,
            "error": str(e)
        }
